#include <ani.h>
#include <array>
#include <iostream>
#include <unistd.h>

static void UpdateFields(ani_env *env, ani_object obj)
{
    std::cout << "Update Field in native" <<std::endl;
    
    static const char *className = "ani_setfield.Foo";
    ani_class cls;
    if (ANI_OK != env->FindClass(className, &cls)) {
        std::cerr << "Not found '" << className << "'" << std::endl;
        return ;
    }
    
    ani_field  hasPointerDeviceField;
    if(ANI_OK != env->Class_FindField(cls, "hasPointerDevice", &hasPointerDeviceField) ) {
         std::cerr << "Get Field Fail" << className << "'" << std::endl;
         return ;
    }

    ani_boolean  value = ANI_TRUE;
    if(ANI_OK != env->Object_SetField_Boolean(obj, hasPointerDeviceField, value) ) {
        std::cerr << "Set Field Fail" << className << "'" << std::endl;
    }
    return;
}


ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result)
{
    ani_env *env;
    if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) {
        std::cerr << "Unsupported ANI_VERSION_1" << std::endl;
        return ANI_ERROR;
    }

    static const char *className = "ani_setfield.Foo";
    ani_class cls;
    if (ANI_OK != env->FindClass(className, &cls)) {
        std::cerr << "Not found '" << className << "'" << std::endl;
        return ANI_ERROR;
    }

    std::array methods = {
        ani_native_function {"UpdateFields", ":", reinterpret_cast<void *>(UpdateFields)},
    };

    if (ANI_OK != env->Class_BindNativeMethods(cls, methods.data(), methods.size())) {
        std::cerr << "Cannot bind native methods to '" << className << "'" << std::endl;
        return ANI_ERROR;
    };

    *result = ANI_VERSION_1;
    return ANI_OK;
}